package com.sky.controller.user;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ArrayUtil;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import com.sky.dto.DishDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.result.Result;
import com.sky.service.IDishFlavorService;
import com.sky.service.IDishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 菜品 前端控制器
 * </p>
 *
 * @author author
 * @since 2024-07-19
 */
@RestController("userDishController")
@RequestMapping("/user/dish")
@RequiredArgsConstructor
@Slf4j
@Api(tags = "用户端-菜品相关接口")
public class DishController {
    private final IDishService dishService;
    private final IDishFlavorService dishFlavorService;
    private final RedisTemplate redisTemplate;

    @ApiOperation("根据分类id查询所有菜品")
    @GetMapping("list")
    public Result<List<DishVO>> list(Long categoryId) {
        //先查询redis里面有没有缓存数据，有的话就不用查询数据库
        String key = "dish_" + categoryId;
        List<DishVO> list = (List<DishVO>) redisTemplate.opsForValue().get(key);
        if(ArrayUtil.isNotEmpty(list)){
            return Result.success(list);
        }

        List<Dish> dish = dishService.lambdaQuery()
                .eq(Dish::getCategoryId, categoryId)
                .list();
        List<DishVO> dishVOList = BeanUtil.copyToList(dish, DishVO.class);
        //根据菜品查询对应的口味
        for (DishVO d : dishVOList) {
            d.setFlavors(dishFlavorService.lambdaQuery()
                    .eq(DishFlavor::getDishId, d.getId())
                    .list());
        }
        redisTemplate.opsForValue().set(key, dishVOList);
        return Result.success(dishVOList);
    }
}
